package com.fyzk.utils.update;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;

import com.fyzk.utils.AppUtil;

/**
 * 应用程序更新工具包
 */
public class UpdateManager {

    private static UpdateManager updateManager;

    private Activity mContext;

    //当前版本号
    private String curVersion;

    public static UpdateManager getUpdateManager() {
        if (updateManager == null) {
            updateManager = new UpdateManager();
        }
        return updateManager;
    }

    public void getVersion(Activity context, final VersionModel versionModel, String flag) {
        mContext = context;
        curVersion = AppUtil.getCurrentVersion(mContext);
        if (!curVersion.equals(versionModel.getVersion().getNewVersion())) {
            doVersionData(context, versionModel);
        } else {
            if ("1".equals(flag)) {
                Toast.makeText(mContext, "当前已经是最新版本", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 显示版本更新通知对话框
     */
    private UpdateDialog mUpdateDialog;
    private void doVersionData(final Context context, final VersionModel versionModel) {
        final VersionModel.Version model = versionModel.getVersion();
        mUpdateDialog = new UpdateDialog(mContext);
        mUpdateDialog.setCanceledOnTouchOutside("0".equals(model.getIsDownloadMust()));
        mUpdateDialog.setNewVersion("最新版本：v" + model.getNewVersion())
                .setCurrentVersion("当前版本：v" + curVersion)
                .setReminder("更新内容\n" + model.getUpdateInfo().replace("\\n", "\n"));
        mUpdateDialog.setUpdateListenter(new UpdateDialog.UpdateClickInterface() {

            @Override
            public void clickView(int type) {
                switch (type) {
                    case 1:
                        if (!"0".equals(model.getIsDownloadMust())) {
                            Toast.makeText(mContext, "为了您更好的体验，务必更新最新版本", Toast.LENGTH_SHORT).show();
                        } else {
                            if (mUpdateDialog != null)
                                mUpdateDialog.dismiss();
                        }
                        break;
                    case 2:
                        //启动一个下载Service
                        if (mUpdateDialog != null)
                            mUpdateDialog.dismiss();

//                        if (TextUtils.isEmpty(versionModel.getAndroid_download())){
//                            versionModel.setAndroid_download(UrlDef.Apk_URL);
//                        }

                        Uri uri = Uri.parse(versionModel.getAndroid_download());
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        context.startActivity(intent);
                        break;
                }
            }
        });
        mUpdateDialog.show();
    }

}
